package com.example.timeplanning_teacher;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.mysql.jdbc.StringUtils;

import org.json.JSONArray;
import org.json.JSONObject;


import java.text.SimpleDateFormat;
import java.util.Locale;

import static com.example.timeplanning_teacher.R.*;

public class FragmentActivity extends AppCompatActivity {

    private String username;
    private String password;
    private String enter_name;
    private Toast timeOut_Toast;
    private Toast updateSuccess;
    private Toast updateFail;
    private Toast passAllSuccess;
    private Toast passAllFail;
    private Toast Success;
    private Toast Failure;
    private SharedPreferences sp;
    private TextView tx_parent_name;
    private Handler handler;
    FragmentParents fragmentParents;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(layout.activity_fragment);
        //getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
//        tx_parent_name = findViewById(R.id.tx_parent_name);
//        tx_username = findViewById(R.id.tx_username);
//        tx_student_name = findViewById(R.id.tx_student_name);

        timeOut_Toast = Toast.makeText(FragmentActivity.this, "网络连接超时", Toast.LENGTH_SHORT);
        updateSuccess = Toast.makeText(FragmentActivity.this,"修改成功",Toast.LENGTH_SHORT);
        updateFail = Toast.makeText(FragmentActivity.this,"修改失败",Toast.LENGTH_SHORT);
        passAllSuccess = Toast.makeText(FragmentActivity.this,"已确认所有计划",Toast.LENGTH_SHORT);
        passAllFail = Toast.makeText(FragmentActivity.this,"确认计划失败",Toast.LENGTH_SHORT);
        Success  = Toast.makeText(FragmentActivity.this,"成功",Toast.LENGTH_SHORT);
        Failure = Toast.makeText(FragmentActivity.this,"失败",Toast.LENGTH_SHORT);
        sp = getSharedPreferences("parent", Context.MODE_PRIVATE);
        username = sp.getString("username","");
        password = sp.getString("password","");
        fragmentParents = FragmentParents.newInstance();
        //tx_parent_name = (TextView) fragmentParents.getView().findViewById(R.id.tx_parent_name);
        //tx_parent_name = fragmentParents.getView().findViewById(id.tx_parent_name);

//        handler = new Handler() {
//            @Override
//            public void handleMessage(Message msg) {
//                super.handleMessage(msg);
//                switch (msg.what) {
//                    case 1:
//                        tx_parent_name.setText(sp.getString("parent_name",""));
//                        break;
//                }
//            };
//        };
//        tx_parent_name = findViewById(R.id.tx_parent_name);
//        tx_parent_name.setText(sp.getString("parent_name",""));
//        tx_username.setText(sp.getString("username",""));
//        tx_student_name.setText(sp.getString("student_name",""));
        //所有信息
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String json = "{\n" +
                            "  \"username\": \"" + username + "\"\n" +
                            "}";
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("http://58.58.36.198:9900/parent/showInformation")
                            .post(RequestBody.create(MediaType.parse("application/json"),json))
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    JSONObject jsonObject=new JSONObject(responseData);
                    JSONArray jsonArray = (JSONArray) jsonObject.get("data");
                    JSONObject parentInformation = jsonArray.getJSONObject(0);
                    boolean hasParentName = parentInformation.get("parent_name").equals(null) ;
                    SharedPreferences.Editor editor = sp.edit();
                    //boolean isEmpty_parent = StringUtils.isEmptyOrWhitespaceOnly((String) parentInformation.getString("parent_name"));
                    if(!hasParentName){
                        editor.putString("parent_name",(String) parentInformation.get("parent_name"));
                    }else {
                        editor.putString("parent_name", "");
                    }
                    editor.putString("username", (String) parentInformation.get("username"));
                    editor.putString("password", (String) parentInformation.get("password"));
                    //boolean isEmpty_student = StringUtils.isEmptyOrWhitespaceOnly((String) parentInformation.getString("student_username"));
                    boolean hasStudentusername = parentInformation.get("student_username").equals(null);
                    if(!hasStudentusername){
                        editor.putString("student_username",(String) parentInformation.get("student_username"));
                    }else {
                        editor.putString("student_username", "");
                    }
                    boolean hasStudentName = parentInformation.get("student_name").equals(null);
                    if(!hasStudentName){
                        editor.putString("student_name",(String) parentInformation.get("student_name"));
                    }else {
                        editor.putString("student_name", "");
                    }
                    editor.commit();
                }catch (Exception e){
                    e.printStackTrace();
                    timeOut_Toast.show();
                }
            }
        }).start();



        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(id.fragment_container,FragmentConfirmPlans.newInstance(),"ff1")
                    .commitNow();
        }


        ImageButton Ibtn_makerules = findViewById(R.id.Ibtn_makerules);
        ImageButton Ibtn_confirmplans = findViewById(R.id.Ibtn_confirmplans);
        ImageButton Ibtn_parents = findViewById(R.id.Ibtn_parents);


        Ibtn_makerules.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getSupportFragmentManager().beginTransaction()
                        .replace(id.fragment_container, FragmentMakeRules.newInstance())
                        .commitNow();
            }
        });


        Ibtn_confirmplans.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getSupportFragmentManager().beginTransaction()
                        .replace(id.fragment_container, FragmentConfirmPlans.newInstance())
                        .commitNow();
            }
        });

        Ibtn_parents.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getSupportFragmentManager().beginTransaction()
                        .replace(id.fragment_container, FragmentParents.newInstance())
                        .commitNow();
            }
        });
    }


    public void quit(View view) {
        Intent intent = new Intent(FragmentActivity.this,MainActivity.class);

        startActivity(intent);
        FragmentActivity.this.finish();
    }

    public void changepsd(View view){
        Bundle bundle = new Bundle();
        Intent intent =new Intent(FragmentActivity.this, CaptchaActivity.class);
        String name = "toChangePsd";
        bundle.putString("name",name);
        intent.putExtra("Message",bundle);
        startActivity(intent);
    }

    //昵称对话框
    public void changeusrname(View view){
        final EditText inputServer = new EditText(FragmentActivity.this);
        AlertDialog.Builder builder = new AlertDialog.Builder(FragmentActivity.this);
        builder.setTitle("输入用户名").setIcon(drawable.changename).setView(inputServer)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                enter_name = inputServer.getText().toString();
                UpdateNameThread updatename = new UpdateNameThread();
                updatename.start();
            }
        });
        builder.show();
    }

    //更新昵称
    public class UpdateNameThread extends Thread{
        public void run(){
            try {

                String json = "{\n" +
                        "  \"parent_name\": \"" + enter_name + "\",\n" +
                        "  \"username\": \"" + username + "\",\n" +
                        "  \"password\": \"" + password + "\"\n" +
                        "}";
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url("http://58.58.36.198:9900/parent/update")
                        .post(RequestBody.create(MediaType.parse("application/json"),json))
                        .build();
                Response response = client.newCall(request).execute();
                String responseData = response.body().string();
                JSONObject jsonObject=new JSONObject(responseData);
                int code=(int)jsonObject.get("code");
                if(code == 100){
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("parent_name",enter_name);
                    updateSuccess.show();
                    //tx_parent_name.setText(sp.getString("parent_name",""));
//                    Message message = new Message();
//                    message.what = 1;
//                    handler.sendMessage(message);
                }
                else{
                    updateFail.show();
                }
            }catch (Exception e){
                e.printStackTrace();
                timeOut_Toast.show();
            }
        }
    }
    //通过所有计划
    public class ConfirmAllThread extends Thread{
        String student_username = sp.getString("student_username","");
        public void run(){
            try {
                String json = "{\n" +
                        "  \"username\": \"" + student_username + "\"\n" +
                        "}";
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url("http://58.58.36.198:9900/task/passAll")
                        .post(RequestBody.create(MediaType.parse("application/json"),json))
                        .build();
                Response response = client.newCall(request).execute();
                String responseData = response.body().string();
                JSONObject jsonObject=new JSONObject(responseData);
                int code=(int)jsonObject.get("code");
                if(code == 100){
                    passAllSuccess.show();
                }
                else{
                    passAllFail.show();
                }
            }catch (Exception e){
                e.printStackTrace();
                timeOut_Toast.show();
            }
        }
    }

    public void bindStudent(View v){
        Intent intent = new Intent(FragmentActivity.this,BindStudentActivity.class);
        startActivity(intent);
    }
    public void aboutApp(View v){
        Intent intent = new Intent(FragmentActivity.this,AboutActivity.class);
        startActivity(intent);
    }
    public void addrule(View view) {
        Intent intent = new Intent(FragmentActivity.this,AddRuleActivity.class);
        startActivity(intent);
    }

    public void getAll_No(View v){
        getSupportFragmentManager().beginTransaction()
                .replace(id.fragment_container, FragmentConfirmPlans.newInstance())
                .commitNow();;
    }

    public void RefreshRules(View v){
        getSupportFragmentManager().beginTransaction()
                .replace(id.fragment_container, FragmentMakeRules.newInstance())
                .commitNow();
    }

    public void confirmAll(View v){
        ConfirmAllThread confirmAllThread = new ConfirmAllThread();
        confirmAllThread.start();
    }

    public void toPlan(View view) {
        Intent intent = new Intent(FragmentActivity.this,PlanActivity.class);
        intent.putExtra("title",setSemesterWeek());//当前日期所在的周，用于打印在第一行的串,也就是标题，整体传过去
        startActivity(intent);
    }

    private String setSemesterWeek() {
        SimpleDateFormat geshi = new SimpleDateFormat("yyyy年MM月dd日", Locale.CHINA);
        java.util.Calendar rili = java.util.Calendar.getInstance(Locale.CHINA);

        rili.setFirstDayOfWeek(java.util.Calendar.MONDAY);

        //当前时间，貌似多余，其实是为了所有可能的系统一致
        rili.setTimeInMillis(System.currentTimeMillis());

        rili.set(java.util.Calendar.DAY_OF_WEEK, java.util.Calendar.MONDAY);
        String monday = geshi.format(rili.getTime()).toString();
        rili.set(java.util.Calendar.DAY_OF_WEEK, java.util.Calendar.SUNDAY);
        String sunday = geshi.format(rili.getTime()).toString();
        return monday+" ~ "+sunday;
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent home = new Intent(Intent.ACTION_MAIN);
            home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            home.addCategory(Intent.CATEGORY_HOME);
            startActivity(home);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}